import { BaseChannel } from "../../core/channel/BaseChannel";
import { registerClass } from "../../../cfw/tools/class_decorator";
import { ADName, SDKState } from "../../SDKDefine";
import { BaseAdMgr } from "../../core/base/BaseAdMgr";
import { GDRewardAd } from "./GDRewardAd";
/**
 * https://gamedistribution.com/developers/sdk/cocos/
 */
@registerClass('GDChannel')
export class GDChannel extends BaseChannel {



    initPlatform() {

        window["GD_OPTIONS"] = {
            "gameId": this.data.gameId,
            "onEvent": (event: any) => {

                console.log(' window["GD_OPTIONS"] ', event.name)
                switch (event.name) {
                    case "SDK_GAME_START":// advertisement done, resume game logic and unmute audio
                        break;
                    case "SDK_GAME_PAUSE":
                        // pause game logic /mute audio
                        break;
                    case "SDK_GDPR_TRACKING":
                        // this event is triggered when your user doesn't want to be tracked
                        break;
                    case "SDK_GDPR_TARGETING":
                        // this event is triggered when your user doesn't want personalised targeting of ads and such
                        break;
                    case "SDK_REWARDED_WATCH_COMPLETE":
                        // this event is triggered when your user completely watched rewarded ad
                        this.onVideoComplete();
                        break;
                    case "AD_ERROR":
                        this.onAdError()
                        break;
                    case "SDK_READY":
                        break;

                }
            }
        };


        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = 'https://html5.api.gamedistribution.com/main.min.js';
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'gamedistribution-jssdk'));
    }


    onVideoComplete() {
        let adMgr: BaseAdMgr = this.getAd(ADName.reward)
        let ad: GDRewardAd = adMgr.get() as GDRewardAd;
        if (ad) {
            ad.onClose({ isEnded: true })
        }
    }

    onAdError() {
        let adMgr: BaseAdMgr = this.getAd(ADName.reward)
        let ad: GDRewardAd = adMgr.get() as GDRewardAd;
        if (ad && ad.isState(SDKState.show)) {
            ad.onError('ad error')
        }
    }


}